package com.yxt.qmgf.tzfe.ctrl;

import javafx.application.Platform;
import javafx.scene.control.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class gameMenuBar extends MenuBar {
    private Callbacks mCallbacks;
    private Menu scoreMenu;

    private static final String SCORE_FILE = "2048_scores.dat"; // 分数记录文件

    /**回调接口*/
    public interface Callbacks {
        void afterRestart();//重新开始
        void afterResetGridSize(int cols,int rows);//重设表格尺寸
        void afterGetMoreScoreInfo();//获取更详细的分数信息
        long getCurrentScore(); // 新增方法获取当前分数
    }

    public gameMenuBar(tzfeInfoController application) {//application供回调方法使用
        mCallbacks=(Callbacks)application;
        //Game菜单
        Menu gameMenu=new Menu("游戏");//游戏
        MenuItem restartMenuItem=new MenuItem("重新开始");//重新开始
        restartMenuItem.setOnAction(e->mCallbacks.afterRestart());
        MenuItem exitMenuItem=new MenuItem("退出");//退出
        exitMenuItem.setOnAction(e-> Platform.exit());
        gameMenu.getItems().addAll(restartMenuItem,exitMenuItem);

        //Setting菜单
        Menu settingMenu=new Menu("设置");//设置
        ToggleGroup tg=new ToggleGroup();//组

        RadioMenuItem r44MenuItem=new RadioMenuItem("尺寸:4x4");
        r44MenuItem.setOnAction(e->mCallbacks.afterResetGridSize(4,4));
        RadioMenuItem r55MenuItem=new RadioMenuItem("尺寸:5x5");
        r55MenuItem.setOnAction(e->mCallbacks.afterResetGridSize(5,5));
        RadioMenuItem r66MenuItem=new RadioMenuItem("尺寸:6x6");
        r66MenuItem.setOnAction(e->mCallbacks.afterResetGridSize(6 ,6));

        r44MenuItem.setToggleGroup(tg);
        r55MenuItem.setToggleGroup(tg);
        r66MenuItem.setToggleGroup(tg);
        settingMenu.getItems().addAll(r44MenuItem,r55MenuItem,r66MenuItem);
        r44MenuItem.setSelected(true);//默认选中4x4

        //Info菜单
        Menu infoMenu=new Menu("信息");//信息
        MenuItem helpMenuItem=new MenuItem("帮助");//帮助
        helpMenuItem.setOnAction(e->{
            Alert alert=new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle(alert.getAlertType().toString());
            alert.setContentText("操作方式:\n"+
                    "向上滑动:方向键↑或键W\n"+
                    "向下滑动:方向键↓或键S\n"+
                    "向左滑动:方向键←或键A\n"+
                    "向右滑动:方向键→或键D\n"+
                    "\n游戏规则:\n"+
                    "相同数字的卡片在靠拢、相撞时会合并\n"+
                    "在操作中合并的卡片会以红色边框凸显\n尽可能获得更大的数字!");
            alert.show();
        });

        infoMenu.getItems().addAll(helpMenuItem);

        //Record菜单
        Menu recordMenu=new Menu("记录");//记录
        MenuItem historyScoreMenuItem=new MenuItem("历史分数");//历史分数
        historyScoreMenuItem.setOnAction(e -> showHistoryScores());
        recordMenu.getItems().addAll(historyScoreMenuItem);


        //Score菜单
        scoreMenu=new Menu("分数");//分数
        MenuItem moreScoreInfo=new MenuItem("更多分数信息");//更多分数信息
        moreScoreInfo.setOnAction(e->mCallbacks.afterGetMoreScoreInfo());
        scoreMenu.getItems().addAll(moreScoreInfo);
        getMenus().addAll(gameMenu,settingMenu,infoMenu,recordMenu,scoreMenu);
    }

    /**获取分数菜单*/
    public Menu getScoreMenu() {
        return scoreMenu;
    }


    private void showHistoryScores() {
        List<ScoreRecord> records = loadHistoryScores();
        long currentScore = mCallbacks.getCurrentScore();

        // 按分数从高到低排序
        records.sort((a, b) -> Long.compare(b.score, a.score));

        // 构建显示内容
        StringBuilder content = new StringBuilder();
        content.append("当前分数: ").append(currentScore).append("\n\n");
        content.append("历史最高分: ").append(records.isEmpty() ? 0 : records.get(0).score).append("\n\n");
        content.append("历史记录:\n");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ScoreRecord record : records) {
            content.append(sdf.format(record.date))
                    .append(" - ")
                    .append(record.score)
                    .append("\n");
        }

        // 显示对话框
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("历史分数记录");
        alert.setHeaderText("2048游戏历史成绩");
        alert.setContentText(content.toString());
        alert.showAndWait();
    }

    public void saveCurrentScore() {
        try {
            List<ScoreRecord> records = loadHistoryScores();
            records.add(new ScoreRecord(mCallbacks.getCurrentScore(), new Date()));
            saveHistoryScores(records);
        } catch (Exception e) {
            System.err.println("保存分数失败: " + e.getMessage());
        }
    }

    /** 从文件加载历史记录 */
    private List<ScoreRecord> loadHistoryScores() {
        File file = new File(SCORE_FILE);
        if (!file.exists()) return new ArrayList<>();

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<ScoreRecord>) ois.readObject();
        } catch (Exception e) {
            System.err.println("加载历史记录失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    /** 保存历史记录到文件 */
    private void saveHistoryScores(List<ScoreRecord> records) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SCORE_FILE))) {
            oos.writeObject(records);
        }
    }

    /** 分数记录数据结构 */
    public static class ScoreRecord implements Serializable {
        private static final long serialVersionUID = 1L;
        final long score;
        final Date date;

        ScoreRecord(long score, Date date) {
            this.score = score;
            this.date = date;
        }
    }
}
